<template>
  <div class="tab-default__container bg-neutral-light" @mouseover="isHover = true" @mouseout="isHover = false">
    <div class="container-content-small">
      <div class="tab-default__tab">
        <div class="tab-blue bg-neutral-light">
          <div class="tab-blue__wrapper flex-center">
            <div class="tab-blue__nav justify-content-center">
              <div class="tab-blue__nav__prev" style="display: none"></div>
              <ul class="tab-blue__list px-4" :id="ulId">
                <li
                  v-for="(item, index) in tabItems"
                  :id="item.id"
                  :key="item.id"
                  class="tab-blue__list__item"
                  :ref="(el) => setTabItemRefs(el, index)"
                  @click="selectTab(item.id)"
                >
                  <button
                    type="button"
                    class="tab-blue__btn"
                    :class="{ 'tab-blue__btn--active': activeItemId === item.id }"
                  >
                    {{ item.name }}
                  </button>
                </li>
                <!-- <span class="tab-blue__strip" style="--strip-width: 103.265625px; --strip-left: 46.875px; --list-scroll-left: 0px; --fix-left: 12px;"></span> -->
                <span class="tab-blue__strip" :style="stripStyle"></span>
              </ul>

              <div class="tab-blue__nav__next" style="display: none"></div>
            </div>
            <!---->
            <div class="tab-blue__filter mt-5 mt-md-3" style="--width: 338px"><!----></div>
          </div>
        </div>
      </div>
      <div class="tab-default__content">
        <div data-aos="fade-in" data-aos-duration="1500" class="aos-init aos-animate">
          <div v-for="(component, index) in pageJsonData" :key="component.id" class="page-item">
            <div class="component-wrapper">
              <component :is="getComponetnBytype(component.type)" :model-value="component" />
            </div>
          </div>
        </div>
        <!----><!---->
      </div>
      <Operate
        v-if="!isPreview"
        v-model:show="isHover"
        @handle-edit="showSetting = true"
        @handle-delete="handleDelete"
        @handle-copy="handleCopy"
        @handle-paste="handlePaste"
      ></Operate>
    </div>
    <Setting v-if="!isPreview" v-model:show="showSetting" :data="modelValue"></Setting>
  </div>
</template>

<script lang="ts" setup>
import { randomString } from "@/utils/common";
// import type { TabDefaultProps, TabDefaultEmits, TabDefaultTab } from './type'
import Setting from "./setting.vue";
// import TabItem from './tabItem.vue'
import { ref, computed, onMounted, onUnmounted, nextTick, watch, defineAsyncComponent } from "vue";
import Operate from '@/common/Operate/index.vue';
// 在组件顶部添加
import TabDefault from "./index.vue";
defineOptions({ name: "TabDefault" });
// 动态导入components目录下的所有组件
// const modules = import.meta.glob("../../components/*/index.vue", { eager: false });
const modules = import.meta.glob("@/components/*/index.vue", { eager: false });

const componentMap = {};
componentMap["TabDefault"] = TabDefault;

// 遍历并注册组件
// 遍历并注册组件，使用文件夹名称作为组件名
for (const path in modules) {
  try {
    // 正确提取文件夹名称
    const pathParts = path.split("/");
    const folderName = pathParts[pathParts.length - 2]; // 文件夹名称
    console.log(`注册组件: ${folderName} from ${path}`); // 调试信息
    componentMap[folderName] = defineAsyncComponent(modules[path]);
  } catch (error) {
    console.error("组件注册失败:", path, error);
  }
}
// 创建一个方法来更新 tabItemRefs
const setTabItemRefs = (el, index) => {
  if (el) {
    tabItemRefs.value[index] = el;
  }
};
const getComponetnBytype = (type) => {
  console.log("cehi =========================");
  return componentMap[type];
};
const props = defineProps({
  modelValue: {
    type: Object,
    default: () => {},
  },

  // 是否预览
  isPreview: {
    type: Boolean,
    default: true,
  },
});
// 监听 tabItems 的变化，确保 tabItemRefs 与之同步
// watch(
//   () => props.modelValue?.data,
//   (newData) => {
//     nextTick(() => {
//       // 清空旧的引用
//       tabItemRefs.value = [];

//       // 在下一个 tick 中重新获取 DOM 引用
//       setTimeout(() => {
//         const tabItems = document.querySelectorAll(".tab-blue__list__item");
//         tabItemRefs.value = Array.from(tabItems);
//       }, 0);
//     });
//   },
//   { deep: true }
// );

const emit = defineEmits(["update:modelValue", "handleDelete", "handleCopy", "handlePaste"]);
// 动画状态
const animating = ref(false);
const animationStage = ref(0); // 0: idle, 1: 扩展, 2: 收缩
const animationFrom = ref(0);
const animationTo = ref(0);
const forceUpdateKey = ref(0);
const ulId = ref(randomString());
// // 切换 Tab
const activeItemId = ref("");
const activeIndex = ref(0);
const tabItemRefs = ref([]);
function selectTab(id) {
  const idx = tabItemRefs.value?.findIndex((item) => item.id === id);
  // if (idx === activeIndex.value || animating.value) return;
  activeItemId.value = id;
  animationFrom.value = activeIndex.value;
  animationTo.value = idx;
  animating.value = true;
  animationStage.value = 1;

  // 先扩展到覆盖所有tab
  setTimeout(() => {
    animationStage.value = 2;
    activeIndex.value = idx;

    // 动画完成后重置状态
    setTimeout(() => {
      animating.value = false;
      animationStage.value = 0;
    }, 300);
  }, 300);
}

const showSetting = ref<boolean>(false);
const isHover = ref<boolean>(false);

// 移除有问题的 activeTabObj 计算属性，因为它引用了不存在的 props.activeTab
// const activeTabObj = computed(() => props.modelValue?.data.find((tab) => tab.id === props.activeTab));

const pageJsonData = computed(() => {
  // 添加更安全的空值检查
  if (!props.modelValue?.data || !Array.isArray(props.modelValue.data)) {
    return [];
  }

  const currentTab = props.modelValue.data[activeIndex.value];
  if (!currentTab) {
    return [];
  }

  return currentTab.componentsDataJson || [];
});

const handleInit = () => {
  if (props.modelValue && props.modelValue.data) {
    // activeItemId.value = props.modelValue?.data[0].id;
    setTimeout(() => {
      selectTab(props.modelValue?.data[0].id);
    }, 0);
    return; // 有数据不用初始化
  }
  const data = {
    id: props.modelValue?.id || randomString(),
    type: "TabDefault",
    containerWidth: "",
    bgColor: "",
    isCenter: "yes",
    data: [
      {
        id: randomString(),
        key: "11111111",
        name: "tab1",
        componentsDataJson: [],
      },
      {
        id: randomString(),
        key: "2222",
        name: "tab2",
        componentsDataJson: [],
      },
      {
        id: randomString(),
        key: "33333",
        name: "tab3",
        componentsDataJson: [],
      },
    ],
  };
  emit("update:modelValue", data);
  activeItemId.value = data.data[0].id;
  // 移除对只读属性的赋值
  // pageJsonData.value = [...data.data[0].componentsDataJson];
};
const tabItems = computed(() => props.modelValue?.data);

handleInit();

const handleDelete = () => {
  emit('handleDelete', props.modelValue.id)
}

const handleCopy = () => {
  emit('handleCopy', props.modelValue)
}

const handlePaste = (type: string) => {
  emit('handlePaste', type)
}

// 计算滑动条样式
const stripStyle = computed(() => {
  forceUpdateKey.value;
  if (!tabItemRefs.value.length) return {};

  let left = 0;
  let width = 0;

  if (!animating.value) {
    const tab = tabItemRefs.value[activeIndex.value];
    if (!tab) return {};
    const style: any = typeof window === 'undefined' ? { paddingLeft: '0', paddingRight: '0' } : window.getComputedStyle(tab);
    left = tab.offsetLeft + parseInt(style.paddingLeft);
    width = tab.clientWidth - parseInt(style.paddingLeft) - parseInt(style.paddingRight);
  } else if (animationStage.value === 1) {
    const from = Math.min(animationFrom.value, animationTo.value);
    const to = Math.max(animationFrom.value, animationTo.value);
    const firstTab = tabItemRefs.value[from];
    const lastTab = tabItemRefs.value[to];
    if (!firstTab || !lastTab) return {};

    const firstStyle: any = typeof window === 'undefined' ? { paddingLeft: '0', paddingRight: '0' } : window.getComputedStyle(firstTab);
    const lastStyle: any = typeof window === 'undefined' ? { paddingLeft: '0', paddingRight: '0' } : window.getComputedStyle(lastTab);

    left = firstTab.offsetLeft + parseInt(firstStyle.paddingLeft);
    width =
      lastTab.offsetLeft +
      lastTab.clientWidth -
      parseInt(lastStyle.paddingRight) -
      (firstTab.offsetLeft + parseInt(firstStyle.paddingLeft));
  } else if (animationStage.value === 2) {
    const tab = tabItemRefs.value[animationTo.value];
    if (!tab) return {};
    const style: any = typeof window === 'undefined' ? { paddingLeft: '0', paddingRight: '0' } : window.getComputedStyle(tab);
    left = tab.offsetLeft + parseInt(style.paddingLeft);
    width = tab.clientWidth - parseInt(style.paddingLeft) - parseInt(style.paddingRight);
  }

  return {
    "--strip-left": `${left}px`,
    "--strip-width": `${width}px`,
    "--tab-strip-color": "#0032a0",
    transition: animating.value ? "all 0.3s cubic-bezier(0.4, 0, 0.2, 1)" : "none",
  };
});

// 添加窗口大小变化监听
const handleResize = () => {
  // 强制重新计算滑块位置
  if (!animating.value) {
    forceUpdateKey.value++;
  }
};
watch(
  tabItems,
  (newVal) => {
    setTimeout(() => {
      if (typeof document === 'undefined') return;
      tabItemRefs.value = [];
      const ulElement = document.getElementById(ulId.value);
      if (!ulElement) return;
      const tabItemsDom = ulElement.querySelectorAll(".tab-blue__list__item");
      tabItemRefs.value = Array.from(tabItemsDom);
      if (newVal && newVal[0]) selectTab(newVal[0].id);
    }, 0);
  },
  { deep: true }
);
// watch(
//   props.modelValue,
//   (newVal) => {
//     nextTick(() => {
//       // 清空旧的引用
//       tabItemRefs.value = [];

//       // 在下一个 tick 中重新获取 DOM 引用
//       setTimeout(() => {
//         const tabItems = document.querySelectorAll(".tab-blue__list__item");
//         tabItemRefs.value = Array.from(tabItems);
//         activeItemId.value = newVal[0].id;
//       }, 0);
//     });
//   },
//   { deep: true }
// );

onMounted(() => {
  if (typeof window !== 'undefined') {
    window.addEventListener("resize", handleResize);
  }
  // 初始计算
  nextTick(() => {
    activeIndex.value = activeIndex.value;
  });
});

onUnmounted(() => {
  if (typeof window !== 'undefined') {
    window.removeEventListener("resize", handleResize);
  }
});
</script>

<style scoped>
.tab-default__container {
  position: relative;
  width: 100%;
}
.tab-blue__wrapper {
  flex-direction: column;
}

.tab-blue__nav {
  display: flex;
  align-items: center;
  width: 100%;
  max-width: 1200px;
  margin: 0 auto;
  position: relative;
  z-index: 1;
  min-height: 38px;
  overflow: hidden;
}

.tab-blue__nav__next,
.tab-blue__nav__prev {
  position: absolute;
  width: 25px;
  height: 38px;
  box-shadow: 0 4px 4px hsla(0, 0%, 100%, 0.2);
  background-color: #f7f7fa;
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1;
}

@media (max-width: 767.98px) {
  .tab-blue__nav__next,
  .tab-blue__nav__prev {
    box-shadow: 0 0 8px rgba(0, 0, 0, 0.22);
  }
}

.tab-blue__nav__next:after,
.tab-blue__nav__prev:after {
  content: "";
  width: 24px;
  height: 38px;
  background-image: url();
  background-position: 50%;
  background-size: cover;
  background-repeat: no-repeat;
  background-color: hsla(0, 0%, 100%, 0);
}

@media (max-width: 1023.98px) {
  .tab-blue__nav__next:after,
  .tab-blue__nav__prev:after {
    width: 14px;
    height: 14px;
  }
}

.tab-blue__nav__prev {
  left: -1px;
}

.tab-blue__nav__prev:after {
  transform: scale(-1);
}

.tab-blue__nav__next {
  right: -1px;
}

.tab-blue__list {
  display: flex;
  align-items: center;
  overflow-x: scroll;
  scroll-behavior: smooth;
  scrollbar-color: transparent;
  scrollbar-width: none;
}

.tab-blue__list::-webkit-scrollbar-track {
  border-radius: 0;
  background-color: transparent;
}

.tab-blue__list::-webkit-scrollbar {
  width: 0;
  height: 0;
  background-color: transparent;
}

.tab-blue__list::-webkit-scrollbar-thumb {
  border-radius: 0;
  background-color: transparent;
}

.tab-blue__list__item {
  padding-right: 4px;
  display: flex;
  text-align: center;
}

@media (max-width: 1023.98px) {
  .tab-blue__list__item {
    padding-right: 0;
  }
}

@media (max-width: 767.98px) {
  .tab-blue__list__item {
    padding-right: 6px;
  }
}

.tab-blue__list__item:first-of-type {
  padding-left: 0;
}

.tab-blue__list__item:last-of-type {
  padding-right: 0;
}

.tab-blue__btn {
  width: auto;
  border: none;
  background: none;
  font-size: 16px;
  font-weight: 400;
  line-height: 1.25;
  letter-spacing: 0.01em;
  white-space: nowrap;
  padding: 8px 20px;
  color: #c0c0c4;
  text-decoration: none;
  transition: color 0.3s ease-in-out;
  outline: none !important;
}

@media (max-width: 1023.98px) {
  .tab-blue__btn {
    font-size: 14px;
    line-height: 1.285;
    letter-spacing: 0.01em;
  }
}

@media (max-width: 767.98px) {
  .tab-blue__btn {
    padding: 4px 10px;
  }
}

.tab-blue__btn:hover {
  color: #0032a0;
}

.tab-blue__btn--active,
.tab-blue__btn:hover.tab-blue__btn--active {
  color: #fff;
}

.tab-blue__btn {
  border: none !important;
  /* 强制移除边框 */
  box-shadow: none !important;
  /* 移除可能存在的阴影 */
}

.tab-blue__strip {
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
  left: 0;
  left: var(--strip-left, 0);
  width: 0;
  width: var(--strip-width, 0);
  height: 100%;
  background: #0032a0;
  background: var(--tab-strip-color, #0032a0);
  transition: left 0.2s ease-in-out, width 0.2s ease-in-out;
  z-index: -1;
  border-radius: 3px;
  overflow: hidden;
  box-shadow: 0 2px 6px 0 rgba(130, 130, 140, 0.12);
}

@media (max-width: 767.98px) {
  .tab-blue__strip {
    max-height: 26px;
  }
}

.tab-blue__filter {
  display: flex;
  align-items: center;
  justify-content: center;
  max-width: 1200px;
  margin: 0 auto;
  width: 100%;
  width: var(--width, 100%);
  position: relative;
  z-index: 1;
}

.tab-blue__filter__filter,
.tab-blue__filter__sort {
  width: 50%;
}

.tab-blue__filter__filter:only-child,
.tab-blue__filter__sort:only-child {
  width: 100%;
}

.tab-blue__filter__filter:last-child,
.tab-blue__filter__sort:last-child {
  margin-right: 8px;
}
</style>
